// Copyright 2007 Google, Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.util;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author jessewilson
 */
public class Reflection {

  public static <T> T newInstance(String className, T defaultValue) {
    Class<T> clas = classForName(className, null);
    if (clas == null) {
      return defaultValue;
    }
    return newInstance(clas, defaultValue);
  }

  public static <T> T newInstance(Class<T> theClass, T defaultValue) {
    try {
      return theClass.newInstance();
    } catch (InstantiationException e) {
      Logger.getLogger(Reflection.class.getName())
          .log(Level.WARNING, "Failed to instantiate class \"" + theClass.getName() + "\"", e);
    } catch (IllegalAccessException e) {
      Logger.getLogger(Reflection.class.getName())
          .log(Level.WARNING, "Failed to access class \"" + theClass.getName() + "\"", e);
    }

    return defaultValue;
  }

  public static <T> Class<T> classForName(String className, Class<T> defaultValue) {
    try {
      return (Class<T>)Class.forName(className);
    } catch(ClassNotFoundException e) {
      Logger.getLogger(Reflection.class.getName())
          .log(Level.WARNING, "Failed to find class \"" + className + "\"", e);
    }

    return defaultValue;
  }
}
